<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>集合</title>
</head>
<body>
	<p>基于ES6中Set类实现集合操作</p>
	<script type="text/javascript">
		class Aggregate {
			constructor () {
				this.item = {}
			}
			has (value) {
				return value in this.item;
			}
			add (value) {
				if (!this.item[value]) {
					this.item[value] = value;
					return true;
				}
				return false;
			}
			remove (value) {
				if (this.item[value]) {
					delete this.item[value]
					return true;
				}
				return false;
			}
			values () {
				return Object.keys(this.item)
			}
			size () {
				return Object.keys(this.item).length;
			}
			clear () {
				this.item = {}
			}
			//取并集
			union (otherSet) {
				let unionSet = new Set(),
					values = this.values(),
					otherVal;
					for (let i = 0; i < values.length; i++) {
						unionSet.add(values[i])
					}
					otherVal = otherSet.values();
					for (let i = 0; i < otherVal.length; i++) {
						unionSet.add(otherVal[i])
					}
					return unionSet;
			}
			//取交集
			interSection (otherSet) {
				let unionSet = new Set(),
					values = this.values();
					for (let i = 0; i < values.length; i++) {
						if (otherSet.has(values[i])) {
							unionSet.add(values[i])
						}
					}
					return unionSet;
			}
			//取差
			diff (otherSet) {
				let diffSet = new Set();
				let values	= this.values();
				for (let i = 0; i < values.length; i++) {
					if (!otherSet.has(values[i])) {
						diffSet.add(values[i]);
					}
				}		
				return diffSet;
			}
			//取子
			subChild (otherSet) {
				let subSet = new Set(),
					values = this.values(),
					_length = this.size(),
					otherSetlen = otherSet.size();
				if (_length > otherSetlen) {
					return false
				} else {
					for (let i = 0; i < _length; i++) {
						if (!otherSet.has(values[i])) {
							return false;
						}
						subSet.add(values[i]);
					}

					return subSet;
				}
			}
		}
		const set1 = new Aggregate();
		set1.add(2);
		set1.add(3);
		set1.add(4);
		set1.add(5);
		console.log(set1.item);
		const set2 = new Aggregate();
		set2.add(3)
		set2.add(4)
		console.log(set2.item);
		console.warn('------取并---------');
		console.log([...set1.union(set2)]);
		console.warn('------取交---------');
		console.log([...set1.interSection(set2)]);
		console.warn('------取差---------');
		console.log([...set1.diff(set2)]);
		console.warn('------取子---------');
		console.log(set2.subChild(set1));
	</script>
</body>
</html>